//
//  LFBReadTopTenArticleViewController.m
//  ONE
//
//  Created by dllo on 16/6/10.
//  Copyright © 2016年 GroupNine. All rights reserved.
//

#import "LFBReadTopTenArticleViewController.h"
#import "LFBNetTool.h"
#import "LFBReadCarouselModel.h"
#import "LFBTopTenArticleModel.h"
#import "LFBReadShortModel.h"
#import "LFBReadSerialModel.h"
#import "LFBReadQuestionModel.h"
#import "LFBReadTopTenArticleCell.h"
#import "LFBSingleReadDetailViewController.h"
#import <UITableView+FDTemplateLayoutCell.h>
#import "UIColor+CarouselBGColor.h"

@interface LFBReadTopTenArticleViewController () <UITableViewDelegate, UITableViewDataSource>

/** 轮播图内容表视图 */
@property (nonatomic, strong) UITableView *tableView;

/** 左上角关闭按钮 */
@property (nonatomic, strong) UIButton *closeButton;

/** 文章标题 */
@property (nonatomic, strong) UILabel *titleLabel;

/** 底部文字 */
@property (nonatomic, strong) UILabel *bottomLabel;

/** 底部图片 */
@property (nonatomic, strong) UIImageView *coverView;

/** 头视图 */
@property (nonatomic, strong) UIView *headerView;

/** 尾视图 */
@property (nonatomic, strong) UIView *footerView;

@end

@implementation LFBReadTopTenArticleViewController
{
    // 数据源数组
    NSArray *dataSource;
    // 底部文字label高
    NSInteger bottomTextLabelHeight;
    // 底部图片视图高
    NSInteger coverViewHeight;
}

- (void)dealloc
{
    _tableView.delegate = nil;
    _tableView.dataSource = nil;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.edgesForExtendedLayout = UIRectEdgeAll;
    self.hideNavigationBar = YES;
    
    [self initData];
    [self createArticleView];
    [self getData];
}

#pragma mark --初始化数据
- (void)initData
{
    coverViewHeight = 168;
    bottomTextLabelHeight = SCREEN_HEIGHT - coverViewHeight;
}

#pragma mark --创建轮播图内容视图
- (void)createArticleView
{
    self.view.backgroundColor = [UIColor colorWithHexString:[_carouseModel.bgcolor substringFromIndex:1]];
    
    _tableView = [[UITableView alloc] initWithFrame:self.view.bounds];
    _tableView.backgroundColor = self.view.backgroundColor;
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [_tableView registerClass:[LFBReadTopTenArticleCell class] forCellReuseIdentifier:kLFBTopTenArticleCellID];
    [self.view addSubview:_tableView];
    [_tableView makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    
    _closeButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_closeButton setImage:[UIImage imageNamed:@"close_normal"] forState:UIControlStateNormal];
    [_closeButton setImage:[UIImage imageNamed:@"close_highlighted"] forState:UIControlStateHighlighted];
    [_closeButton addTarget:self action:@selector(didClickedCloseButton) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_closeButton];
    [_closeButton makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.equalTo(44);
        make.top.equalTo(self.view).offset(20);
        make.left.equalTo(self.view);
    }];
    
    _headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 64)];
    _headerView.backgroundColor = _tableView.backgroundColor;
    _titleLabel = [UILabel new];
    _titleLabel.textColor = [UIColor whiteColor];
    _titleLabel.font = FontWithSize(18);
    _titleLabel.text = _carouseModel.title;
    _titleLabel.textAlignment = 1;
    
    [_headerView addSubview:_titleLabel];
    [_titleLabel makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(_headerView).insets(UIEdgeInsetsMake(-5, 0, 5, 0));
    }];
    _tableView.tableHeaderView = _headerView;
    
    _footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    _footerView.backgroundColor = _tableView.backgroundColor;
    _bottomLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 0, SCREEN_WIDTH - 40, bottomTextLabelHeight)];
    _bottomLabel.backgroundColor = _footerView.backgroundColor;
    _bottomLabel.textAlignment = 1;
    _bottomLabel.textColor = [UIColor whiteColor];
    _bottomLabel.font = FontWithSize(18);
    _bottomLabel.text = _carouseModel.bottom_text;
    _bottomLabel.numberOfLines = 0;
    [_footerView addSubview:_bottomLabel];
    
    _coverView = [[UIImageView alloc] initWithFrame:CGRectMake(0, bottomTextLabelHeight, SCREEN_WIDTH, coverViewHeight)];
    _coverView.backgroundColor = _footerView.backgroundColor;
    // 设置内容模式为填充
    _coverView.contentMode = UIViewContentModeScaleAspectFill;
    [_coverView sd_setImageWithURL:[NSURL URLWithString:_carouseModel.cover] placeholderImage:nil];
    [_footerView addSubview:_coverView];
}

#pragma mark --左上角关闭按钮点击方法
- (void)didClickedCloseButton
{
    [self dismissViewControllerAnimated:NO completion:NULL];
}

#pragma mark --显示单个阅读详情
- (void)showSingleReadDetailsWithReadModel:(BaseModel *)model type:(LYLReadType)type
{
    LFBSingleReadDetailViewController *singleReadDetailsViewController = [[LFBSingleReadDetailViewController alloc] init];
    singleReadDetailsViewController.readType = type;
    singleReadDetailsViewController.readModel = model;
    [self.navigationController pushViewController:singleReadDetailsViewController animated:YES];
}

#pragma mark --请求数据
- (void)getData
{
    [LFBNetTool getNetWithURL:[NSString stringWithFormat:@"%@/%@", LYLApiReadingCarousel, _carouseModel.id] Body:nil Header:nil Response:LFBJSON Success:^(id result) {
        if ([result[@"res"] integerValue] == 0) {
            NSArray *data = result[@"data"];
            NSMutableArray *datas = [NSMutableArray array];
            for (NSDictionary *dic in data) {
                LFBTopTenArticleModel *articleModel = [[LFBTopTenArticleModel alloc] initWithDic:dic];
                [datas addObject:articleModel];
            }
            dataSource = datas;
            [_tableView reloadData];
            _tableView.tableFooterView = _footerView;
        }
    } Failure:^(NSError *error) {
        
    }];
}

#pragma mark --UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (scrollView.contentOffset.y >= CGRectGetMinY(_footerView.frame)) {
        CGFloat diff = scrollView.contentOffset.y - CGRectGetMinY(_footerView.frame);
        CGFloat scale = 1 + diff / coverViewHeight;
        // 设置缩放比例
        CGAffineTransform transform = CGAffineTransformMakeScale(scale, scale);
        CGRect frame = self.coverView.frame;
        frame.origin.y = bottomTextLabelHeight + diff / 2;
        self.coverView.frame = frame;
        
        [UIView animateWithDuration:0.01 delay:0 options:UIViewAnimationOptionAllowUserInteraction | UIViewAnimationOptionBeginFromCurrentState | UIViewAnimationOptionCurveLinear animations:^{
            _coverView.transform = transform;
        } completion:NULL];
    }
}

#pragma mark --UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    LFBReadTopTenArticleCell *cell = [tableView dequeueReusableCellWithIdentifier:kLFBTopTenArticleCellID forIndexPath:indexPath];
    [cell configureCellWithTopTenArticleModel:dataSource[indexPath.row] atIndexPath:indexPath];
    cell.backgroundColor = _tableView.backgroundColor;
    cell.contentView.backgroundColor = _tableView.backgroundColor;
    
    return cell;
}

#pragma mark --UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return [tableView fd_heightForCellWithIdentifier:kLFBTopTenArticleCellID cacheByIndexPath:indexPath configuration:^(LFBReadTopTenArticleCell *cell) {
        [cell configureCellWithTopTenArticleModel:dataSource[indexPath.row] atIndexPath:indexPath];
    }];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    LFBTopTenArticleModel *articleModel = dataSource[indexPath.row];
    if ([articleModel.type isEqualToString:@"1"]) {   //短篇
        LFBReadShortModel *shortModel = [[LFBReadShortModel alloc] init];
        shortModel.content_id = articleModel.item_id;
        [self showSingleReadDetailsWithReadModel:shortModel type:LYLReadTypeShort];
    }
    else if ([articleModel.type isEqualToString:@"2"])   //连载
    {
        LFBReadSerialModel *serialModel = [[LFBReadSerialModel alloc] init];
        serialModel.id = articleModel.item_id;
        serialModel.number = [@(articleModel.number) stringValue];
        [self showSingleReadDetailsWithReadModel:serialModel type:LYLReadTypeSerial];
    }
    else if ([articleModel.type isEqualToString:@"3"])   //问答
    {
        LFBReadQuestionModel *questionModel = [[LFBReadQuestionModel alloc] init];
        questionModel.question_id = articleModel.item_id;
        questionModel.question_title = articleModel.title;
        [self showSingleReadDetailsWithReadModel:questionModel type:LYLReadTypeQuestion];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
